package client

import (
	"context"
	"google.golang.org/grpc"
	"time"

	"chainmaker/pb/protogo"
)

const (
	fiveSecond = time.Second * 5
)

//RpcClient a rpc client to get args and send result
type RpcClient struct {
	client protogo.ContractInvokeClient
}

// NewRpcClient new a rpc client instance
func NewRpcClient(serverAddress string) (*RpcClient, error) {
	rpcClient := new(RpcClient)
	grpcClient, err := grpc.Dial(serverAddress, grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := protogo.NewContractInvokeClient(grpcClient)
	rpcClient.client = client
	return rpcClient, nil
}

// SendResult send contract execute result to server
func (rc *RpcClient) SendResult(result *protogo.ExecuteResult) (*protogo.ExecuteResultResponse, error) {
	timeout, cancelFunc := context.WithTimeout(context.Background(), fiveSecond)
	defer cancelFunc()
	return rc.client.ExecResult(timeout, result, grpc.EmptyCallOption{})
}
